/**
 * Created by Administrator on 2017/5/8.
 */

var redis_db = require('../config/redis2Qrcode');
var getHmUrlDao = module.exports;

getHmUrlDao.getUrl = function (data, cb) {
    if(!data) {
        cb(new Error(500));
    } else {
        redis_db.get(data.uid, function(err, result) {
            if(err) {
                console.log(err);
                cb(false);
            } else {
                var hmInfo = JSON.parse(result);
                if(!result) {
                    cb('未找到此二维码！');
                    return;
                }
                if(hmInfo[data.hid] == undefined) {
                    cb('未找到此二维码！');
                    return;
                } else {
                    var info = [];
                    for(var i=0;i<=hmInfo[data.hid].p; i++) {
                        if(hmInfo[data.hid].qrs[i] != undefined) {
                            if(hmInfo[data.hid].qrs[hmInfo[data.hid].curQid] != undefined && hmInfo[data.hid].qrs[hmInfo[data.hid].curQid].c < hmInfo[data.hid].threshold) {
                                hmInfo[data.hid].qrs[hmInfo[data.hid].curQid].c = parseInt(hmInfo[data.hid].qrs[hmInfo[data.hid].curQid].c) + 1;
                                info.push(hmInfo[data.hid].qrs[hmInfo[data.hid].curQid].picUrl);
                                break;
                            } else if( hmInfo[data.hid].qrs[i].c < hmInfo[data.hid].threshold) {
                                hmInfo[data.hid].qrs[i].c = parseInt(hmInfo[data.hid].qrs[i].c) + 1 ;
                                info.push(hmInfo[data.hid].qrs[i].picUrl);
                                break;
                            }
                        }
                    }

                    var sum = 0;
                    for(var i=0;i<=hmInfo[data.hid].p; i++) {
                        if(hmInfo[data.hid].qrs[i] != undefined) {
                            sum +=  parseInt(hmInfo[data.hid].qrs[i].c);
                            //console.log(hmInfo[data.hid].t);
                        }
                    }
                    hmInfo[data.hid].t = sum;
                    redis_db.set(data.uid, JSON.stringify(hmInfo), '', function(e){
                        if(e) {
                            console.log(e);
                            cb('扫取二维码失败！');
                        }
                        if(info.length == 0){
                            cb('未找到有效二维码')
                        } else {
                            cb(null, info);
                        }
                    });
                }
            }
        });
    }
}